package com.arrogames.rgblabyrinth.menu {
	import com.arrogames.rgblabyrinth.AssetManager;
	import com.arrogames.rgblabyrinth.menu.components.MetaGameRenderer;
	import com.arrogames.rgblabyrinth.menu.events.StartGameEvent;
	import com.arrogames.rgblabyrinth.model.storage.GameMetaData;
	import com.arrogames.util.UIUtil;
	
	import feathers.controls.Button;
	import feathers.controls.Label;
	import feathers.controls.List;
	import feathers.controls.Screen;
	import feathers.data.ListCollection;
	
	import starling.display.DisplayObject;
	import starling.events.Event;
	
	public class ContinueGameScreen extends Screen {
		
		private var _savegames:ListCollection;
		
		public function ContinueGameScreen() {
			super();
			
			_savegames = new ListCollection();
		}
		
		override protected function initialize():void {
			super.initialize();
			
			addChild(createTitleDisplay());
			addChild(createGameListDisplay());
			addChild(UIUtil.createButton(AssetManager.instance.getTexture("backBtn"), 20, 600-128-20, onBackClick));
		}
		
		private function createTitleDisplay():DisplayObject {
			var label:Label = new Label();
			label.text = "Choose a game to continue with:";
			label.x = 200;
			label.y = 50;
			return label;
		}
		
		private function createGameListDisplay():DisplayObject {
			var list:List = new List();
			list.x = 100;
			list.y = 100;
			list.width = 600;
			list.height = 400;
			
			list.dataProvider = _savegames;
			list.addEventListener( Event.CHANGE, listChangeHandler );
			
			list.itemRendererType = MetaGameRenderer;
			
			return list;
		}
		
		private function listChangeHandler( event:Event ):void {
			var list:List = event.currentTarget as List;
			var game:GameMetaData = list.selectedItem as GameMetaData;
			if (game != null) {
				dispatchEvent(new StartGameEvent(StartGameEvent.CONTINUEGAME, game));
			}
		}
		
		private function onBackClick(event:Event):void {
			var button:Button = event.currentTarget as Button;
			this.owner.showScreen(RGBNavigator.MAINMENU);
		}
		
		public function set savegames(value:Array):void {
			_savegames.removeAll();
			for (var i:int=0; i < value.length; i++) {
				_savegames.addItem(value[i]);
			}
		}
	}
}